package com.cyys.modules.system.service.file;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyys.common.ql.AR;
import com.cyys.common.services.CyysBaseService;
import com.cyys.modules.system.dao.file.FileEntryDao;
import com.cyys.modules.system.model.file.FileEntry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("fileEntryService")
@Transactional(readOnly = true)
public class FileEntryService extends CyysBaseService<FileEntryDao, FileEntry> {

	/**
	 * 获取单条数据
	 * 
	 * @param fileUrl
	 *            null,查询所有数据 0:查询未删除的数据,1:查询已删除的数据
	 * @return
	 */
	public FileEntry getByFileUrl(String fileUrl)  {
		return dao.getByFileUrl(fileUrl);
	}

	@Transactional(readOnly = false)
	public List<FileEntry> saveList(List<FileEntry> list)  {
		List<FileEntry> returnList = new ArrayList<FileEntry>();
		for (FileEntry fileEntry : list) {
			dao.insert(fileEntry);
			fileEntry.setIsDelete(0);
			returnList.add(fileEntry);
		}
		return returnList;
	}

	/**
	 * 移动文件到默认目录
	 * @param dirId
	 */
	@Transactional(readOnly = false)
	public void moveAllFile(String dirId)  {
		dao.moveAllFile(dirId);
	}

	@Transactional(readOnly = false)
	public AR moveFile(String id, String dirId)  {
		FileEntry fileEntry = new FileEntry();
		fileEntry.setId(id);
		fileEntry.setDirId(dirId);
		dao.updateById(fileEntry);
		return AR.ok("文件移动成功");
	}

	@Transactional(readOnly = false)
	public AR moveFiles(String ids, String dirId)  {
		String[] idsInt = ids.split(",");
		for(int i = 0; i <idsInt.length;i++){
			FileEntry fileEntry = new FileEntry();
			fileEntry.setId(idsInt[i]);
			fileEntry.setDirId(dirId);
			dao.updateById(fileEntry);
		}
		return AR.ok("文件移动成功");
	}

    public IPage listRecycle(Page page, FileEntry fileEntry) {
		int count = dao.selectRecycleCount(fileEntry);
		if (count != 0) {
			long start =  (page.getCurrent() - 1) * page.getSize();
			page.setRecords(dao.selectRecycle(start, page.getSize(), fileEntry));
		}
		page.setTotal(count);
		return page;
    }

}
